<?php
namespace app\h5api\controller;

use app\common\model\Collection;
use app\common\model\Commit;
use app\common\model\Footprint;
use app\common\model\ProductsType as ProductsTypeModel;
use app\common\model\Products as ProductsModel;
use app\common\model\Shops;
use app\common\model\ShopsBanner;
use app\h5api\validate\Product;

class Products extends Base
{
    /**
     * @route('h5/ProductList')
     * 商品列表
     */
    public function ProductList()
    {
//        $ProductsTypeModel = new ProductsTypeModel();
        $ProductModel = new \app\common\model\Products();
        $limit = input('get.limit') ? input('get.limit') : 10;
        $validate = new Product();
        $ssort = input('get.ssort');
        $nsort = input('get.nsort');
        if(!$validate->scene('paixu')->check(['ssort'=>$ssort,'nsort'=>$nsort])){
            $this->result('',-1,$validate->getError());
        }

        $pwhere = [
            "product_name" => input('get.product_name'),
            "shop_id" => input('get.shop_id'),
            "type_id" => input('get.type_id'),
            "state" => 1,
            "approved" => 2,
            "shop_state" => 1,
            "shop_approved" => 1,
            "is_del" => 1,
            "class_id" => 1,
            "lon" => $this->lon,
            "lat" => $this->lat,
        ];
        $orderby = [];
        empty($ssort)?'':$orderby['salecount'] = $ssort;
        empty($nsort)?'':$orderby['createat'] = $nsort;
//        var_dump($orderby);die;
        $item = $this->getfieldstring('p.*');
        $products = $ProductModel->get_product_list($pwhere,$orderby,$item,$limit);
        $this->result($products,1,'返回成功');
    }

    /**
     * @route('h5/GetProductDetail')
     * 普通商品获取详情
     */
    public function GetProductDetail()
    {
        $ProductModel = new \app\common\model\Products();
        $FootModel = new Footprint();
        $productid = input('get.product_id');
        $userinfo = $this->GetUserInfo();
        $data = [
            'product_id' => $productid,
            'class_id' => 1,
        ];
        $item = '*';
        $item = $this->getfieldstring($item);
        $products = $ProductModel->get_product_detail($data,$item);
        $is_collect = $ProductModel->product_is_collect($userinfo,$productid);
        $products['is_collect'] = $is_collect;
        $FootModel->record($this->_userid,$productid);
        $data = [
            "products" => $products,
        ];
        $this->result($data,1,'返回成功');
    }

    /**
     * @route('h5/GetProductCommit')
     * 商品评价列表
     */
    public function GetProductCommit()
    {
        $model = new Commit();
        $productid = input('get.product_id');
        $commits = $model->get_product_commit($productid,$this->limit);
        $this->result($commits,1,'返回成功');
    }

    /**
     * @route('h5/CollectProduct')
     * 用户收藏商品
     */
    public function CollectProduct()
    {
        $CollectModel = new Collection();
        $productid = input('post.product_id');
        $stockid = input('post.stock_id',0);
        $res = $CollectModel->record($this->_userid,$productid,$stockid);
        if($res['code'] == -1){
            $this->result('',-1,'收藏操作失败');
        }
        $this->result([],1,$res['msg']);
    }

    /**
     * @route('h5/GetHotProduct')
     * 获取热门商品列表
     */
    public function GetHotProduct()
    {
        $ProductModel = new \app\common\model\Products();
        $shopid = input('get.shop_id');
        $condition = [
            "shop_id" => $shopid,
            "state" => 1,
            "approved" => 2,
            "shop_state" => 1,
            "shop_approved" => 1,
            "class_id" => 1,
            "is_del" => 1,
            "lon" => $this->lon,
            "lat" => $this->lat,
        ];
        $item = "p.*";
        $item = $this->getfieldstring($item);
        $hots = $ProductModel->get_hot_list($condition,$item,$limit = 9);
        $this->result($hots,1,'成功');
    }

    /**
     * @route('h5/GetUncommonProduct')
     * 获取非普通商品列表
     */
    public function GetUncommonProduct()
    {
        $ProductModel = new \app\common\model\Products();
        $shopid = input('get.shop_id');
        $typeid = input('get.type_id','');
        $classname = input('get.class_name');
        $productname = input('get.product_name');
        $limit = input('get.limit') ? input('get.limit') : 9;
        switch($classname){
            case "exchange":
                $class_id = 2;
                break;
            case "love":
                $class_id = 3;
                break;
            case "team":
                $class_id = 4;
                break;
            default:
                $this->result([],-1,'类型错误');
                break;
        }
        $condition = [
            "state" => 1,
            "approved" => 2,
            "is_del" => 1,
            "shop_approved" => 1,
            "shop_state" => 1,
            "stock_del" => 1,
            "class_id" => $class_id,
            "product_name" => $productname,
            "lon" => $this->lon,
            "lat" => $this->lat,
        ];
        if(isset($shopid)){
            $condition['shop_id'] = $shopid;
        }
        if($class_id == 2){
            $condition['product_name'] = $productname;
            $condition['type_id'] = $typeid;
        }
        $ssort = input('get.ssort');
        $nsort = input('get.nsort');
        $validate = new Product();
        if(!$validate->scene('paixu')->check(['ssort'=>$ssort,'nsort'=>$nsort])){
            $this->result('',-1,$validate->getError());
        }
        $orderby = [];
        empty($ssort)?'':$orderby['salecount'] = $ssort;
        empty($nsort)?'':$orderby['createat'] = $nsort;
        $item = 'p.*,ps.p_s_id,ps.p_s_name,ps.g_m_details,ps.g_m_paper,ps.stock,s.shop_name';
        $item = $this->getfieldstring($item);
        $hots = $ProductModel->get_uncommon_list($condition,$orderby,$item,$limit);
        $this->result($hots,1,'成功');
    }

    /**
     * @route('h5/GetShowProduct')
     * 获取展示菜品列表
     */
    public function GetShowProduct()
    {
        $ProductModel = new ProductsModel();
        $shopid = input('get.shop_id');
        $condition = [
            "shop_id" => $shopid,
            "state" => 1,
            "approved" => 2,
            "shop_state" => 1,
            "shop_approved" => 1,
            "class_id" => 6,
            "is_del" => 1,
        ];
        $item = "p.*";
        $hots = $ProductModel->get_show_list($condition,$item,'',$this->limit);
        $this->result($hots,1,'成功');
    }

    /**
     * @route('h5/GetTeamProductDetail')
     * 团餐商品获取详情
     */
    public function GetTeamProductDetail()
    {
        $ProductModel = new \app\common\model\Products();
//        $FootModel = new Footprint();
        $productid = input('get.product_id');
        $stockid = input('get.stock_id');
        $userinfo = $this->GetUserInfo();
        $data = [
            'product_id' => $productid,
            'class_id' => 4,
            'stock_id' => $stockid,
        ];
        $item = 'p.*,ps.p_s_name,g_m_details,g_m_paper,stock,ps.p_s_id';
        $item = $this->getfieldstring($item);
        $products = $ProductModel->get_uncommon_product_detail($data,$item);
//        $FootModel->record($this->_userid,$productid);
        $is_collect = $ProductModel->product_is_collect($userinfo,$productid,$stockid);
        $products['is_collect'] = $is_collect;
        $data = [
            "products" => $products,
        ];
        $this->result($data,1,'返回成功');
    }

    /**
     * @route('h5/GetUncommonProductDetail')
     * 非普通商品获取商品详情
     */
    public function GetUncommonProductDetail()
    {
        $ProductModel = new \app\common\model\Products();
//        $FootModel = new Footprint();
        $productid = input('get.product_id');
        $stockid = input('get.stock_id');
        $userinfo = $this->GetUserInfo();
        $data = [
            'product_id' => $productid,
            'class_ids' => [2,3,4],
            'stock_id' => $stockid,
        ];
        $item = 'p.*,ps.p_s_name,g_m_details,g_m_paper,stock,ps.p_s_id';
        $item = $this->getfieldstring($item);
        $products = $ProductModel->get_uncommon_product_detail($data,$item);
//        $FootModel->record($this->_userid,$productid);
        $is_collect = $ProductModel->product_is_collect($userinfo,$productid,$stockid);
        $products['is_collect'] = $is_collect;
        $data = [
            "products" => $products,
        ];
        $this->result($data,1,'返回成功');
    }

    function getfieldstring($item){
        if($this->_userid != 0) {
            $userinfo = $this->GetUserInfo();
            if($userinfo['utype'] == 2){
                $item .= ',p.mprice as sale_price';
            } else {
                $item .= ',p.sprice as sale_price';
            }
        } else {
            $item .= ',p.sprice as sale_price';
        }
        return $item;
    }

    /**
     * @route('h5/Shopinfo')
     * 商铺详情
     */
    public function Shopinfo()
    {
        $shopModel = new Shops();
        $shop_id = input('get.shop_id');
        $field =[
            '*',
            '(select count(order_id) from ddt_order where shop_id = ddt_shops.shop_id and order_status = 4 and order_type = 4) as sales_volume'
        ];
        if(!empty($this->lon) && !empty($this->lat)){
            $field[] = "FLOOR((st_distance (point (lon, lat), point({$this->lon}, {$this->lat})) * 111195) +1) AS distance";
        }
        $shop = $shopModel->getOneShop($shop_id,$field);
        $data['shop'] = empty($shop)?null:$shop->toArray();
        $data['shop_banner'] = [];
        if(!empty($data['shop']) && ($data['shop']['shop_type'] == 1 || $data['shop']['shop_type'] == 3)){
            $bannerModel = new ShopsBanner();
            $banners = $bannerModel->get_list(['shop_id'=>$shop_id,'type'=>1],'sort','*',3);
            $banners = $banners->toArray();
            $data['shop_banner'] = $banners['data'];
        }
        $data['shop']['is_can_reserve'] = false;
        if(!empty($shop['reserve_info'])){
            $reserve_info = json_decode($shop['reserve_info'],true);
            unset($shop['reserve_info']);
            $time_ranges = $reserve_info['time_ranges'];
            foreach($time_ranges as $value){
                $time_range = explode(" - ",$value);
                $all_time[] = $time_range[0];
                $all_time[] = $time_range[1];
                $this->get_time_array($time_range[1],$time_range[0]);
            }
            if(!empty($this->time_callback)){
                $data['shop']['is_can_reserve'] = true;
            }
        }
        unset($data['shop']['reserve_info']);
        $this->result($data,1,'返回成功');
    }

    /**
     * @route('h5/UserReserve')
     * 用户订座数据
     */
    public function UserReserve()
    {
        $shopModel = new Shops();
        $shop_id = input('get.shop_id');
        $post_date = input('get.time_date',date('Y-m-d',time()));
        $shop = $shopModel->getOneShop($shop_id,'*');
        if(empty($shop)){
            $this->result([],-1,'不存在该店铺');
        }
        if(empty($shop['reserve_info'])){
            $this->result([],-1,'店铺暂未提供订座，请联系商家');
        }
        $reserve_info = json_decode($shop['reserve_info'],true);
        unset($shop['reserve_info']);
//        var_dump($reserve_info);
        $time_ranges = $reserve_info['time_ranges'];
        foreach($time_ranges as $value){
            $time_range = explode(" - ",$value);
//            var_dump($time_range);
            $all_time[] = $time_range[0];
            $all_time[] = $time_range[1];
            $this->get_time_array($time_range[1],$time_range[0]);
//            var_dump($this->time_callback);
        }
        $thedaytime = time();
//        if(empty($this->time_callback)){
//            $thedaytime = strtotime("+1 day",strtotime($thedaytime));
//        }
        $time_arr = $this->time_all_callback;
        if(date('Y-m-d',time()) == $post_date){
            $time_arr = $this->time_callback;
        }
//        var_dump(array_unique($time_arr));
        $shop['persons'] = $reserve_info['persons'];
//        $w=date('w');
//        $week=array(
//            "0"=>"周日",
//            "1"=>"周一",
//            "2"=>"周二",
//            "3"=>"周三",
//            "4"=>"周四",
//            "5"=>"周五",
//            "6"=>"周六"
//        );
        $shop['date_time'] = [
            'now_time' => $thedaytime,
            'now_date' => date('Y-m-d',$thedaytime),
//            'week' => $week[$w],
        ];
        $shop['time_arr'] = $time_arr;
//        var_dump($shop);die;
//        var_dump($shop);
        $this->result($shop,1,'返回成功');
    }

    private $time_callback = [];
    private $time_all_callback = [];

    private function get_time_array($end_time,$begin_time,$MINUTE = 30){
        if($end_time >= $begin_time){
            if($begin_time > date("H:i",time())){
                $this->time_callback[] = $begin_time;
            }
            $this->time_all_callback[] = $begin_time;
//            var_dump($this->time_callback);
            $thetime = date("H:i",strtotime("+$MINUTE MINUTE",strtotime($begin_time)));
            if($thetime == "00:00"){
                return;
            }
            $this->get_time_array($end_time,$thetime);
        }
    }
}
